package cn.net.isir.controller.manager;

import cn.net.isir.common.ResultObject;
import cn.net.isir.common.TokenManager;
import cn.net.isir.core.BasicController;
import cn.net.isir.dao.RoleDao;
import cn.net.isir.entity.*;
import cn.net.isir.service.*;
import cn.net.isir.utils.JSONUtils;
import cn.net.isir.utils.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liuxubo
 * @filename UserController.java
 * @package cn.net.isir.controller.manager
 * @email lxb@isir.net.cn
 * @date 2019/02/25
 * @comment
 * @since 1.8
 */
@RestController
@RequestMapping("/user")
public class UserController extends BasicController<User> {
    @Resource
    private UserService userService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private UserValidInfoService userValidInfoService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private UserOrgService userOrgService;
    @Resource
    private OrganizationsService organizationsService;
    @Resource
    private CRMUserManagerService crmUserManagerService;
    @Resource
    private RoleDao roleDao;

    /**
     * 根据用户id查询信息
     *
     * @param e 包含用户名(用于搜索)
     * @return 列表
     */
    @RequestMapping(value = "/listByUser", method = RequestMethod.GET)
    public ResultObject selectListByUser(User e) {
        StopWatch stopWatch = new StopWatch("cn.net.isir.controller.manager.UserController.selectListByUser");
        stopWatch.start();
        // 查询当前用户的机构id
        String userId = TokenManager.getTokenId();
        UserOrg userOrg = new UserOrg();
        userOrg.setUserId(userId);
        UserOrg userOrg1 = userOrgService.selectOne(userOrg);
        // 查询子组织机构列表
        List<Organizations> organizationsList = organizationsService.selectSubList(userOrg1.getOrgId());
        if (organizationsList == null || organizationsList.size() != 0){
            // 转化为逗号分隔的字符串
            String orgIds = StringUtils.collectionsToCommas(
                    organizationsList.stream().map(Organizations::getId).collect(Collectors.toList()));
            PageInfo<User> pageInfo  = userService.selectSubUserPageList(orgIds,
                    e.getUsername(), e.getPageNo(), e.getPageSize());
            // 格式化数据
            JSONObject jo = JSONUtils.toJSONObject(pageInfo);
            JSONArray ja = new JSONArray();
            if(pageInfo != null){
                for (User user : pageInfo.getList()) {
                    JSONObject subJO = JSONUtils.toJSONObject(user);
                    // 查询用户名，联系方式
                    UserInfo userInfo = userInfoService.selectByUserId(user.getId());
                    subJO.put("name", userInfo.getName());
                    subJO.put("tel", userInfo.getTel());
                    // 组织机构
                    UserOrg userOrg2 = userOrgService.selectByUserId(user.getId());
                    Organizations organizations = organizationsService.selectByPrimaryKey(userOrg2.getOrgId());
                    if (organizations != null) {
                        subJO.put("org", organizations.getOrgName());
                    }
                    // 所属角色
                    List<Role> roleList = userRoleService.selectRoleListByUserId(user.getId());
                    if (roleList != null && roleList.size() > 0) {
                        subJO.put("role", roleList.get(0).getRoleName());
                    }
                    ja.add(subJO);
                }
            }
            jo.put("list", ja);
            stopWatch.stop();
            System.out.println(stopWatch.prettyPrint());
            return new ResultObject(200, "success", jo);
        }else{
            return new ResultObject(200, "success", new PageInfo<>());
        }
    }

    /**
     * 查询信息
     *
     * @param id 主键
     * @return 结果
     */
    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
    public ResultObject query(@PathVariable String id) {
        UserDto dto = new UserDto();
        // 查询到用户信息
        User user = userService.selectByPrimaryKey(id);
        // 查询其他用户信息
        UserInfo userInfo = userInfoService.selectByUserId(user.getId());
        // 查询用户组织机构
        UserOrg userOrg = userOrgService.selectByUserId(user.getId());
        // 查询用户角色
        List<Role> roleList = userRoleService.selectRoleListByUserId(user.getId());
        StringBuilder roleSB = new StringBuilder();
        String roles = null;
        roleList.forEach(item -> roleSB.append(item.getId()).append(","));
        if (roleSB.length() > 0) {
            roles = roleSB.substring(0, roleSB.length() - 1);
        }
        // 组合数据返回
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setName(userInfo.getName());
        dto.setTel(userInfo.getTel());
        dto.setOrg(userOrg.getOrgId());
        dto.setRole(roles);
        dto.setStatus(user.getStatus());
        // 查询角色信息
        return new ResultObject(200, "success", dto);
    }

    /**
     * 增加用户
     *
     * @param map 增加信息
     * @return 结果
     */
    @Override
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResultObject add(@RequestBody Map map) {
        // 接收参数
        String username = String.valueOf(map.get("username"));
        String pwd = String.valueOf(map.get("pwd"));
        String name = String.valueOf(map.get("name"));
        String mobile = String.valueOf(map.get("mobile"));
        String status = String.valueOf(map.get("status"));
        String org = String.valueOf(map.get("org"));
        String role = String.valueOf(map.get("role"));
//判断手机号是否已存在
        UserInfo ui = new UserInfo();
        ui.setTel(mobile);
        ui = userInfoService.selectOne(ui);
        if(ui !=null){
            ResultObject ro = new ResultObject();
            ro.setResult(505);
            ro.setMessage("Tel[" + mobile+ "] is already exist!");
            return ro;
        }
        // 新增用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(pwd);
        user.setStatus(status);
        user.setCreateUser(TokenManager.getTokenId());
        user.setUserType("salesman");
        // 新增用户详情
        UserInfo userInfo = new UserInfo();
        userInfo.setName(name);
        userInfo.setTel(mobile);
        userInfo.setCreateUser(TokenManager.getTokenId());
        // 新增用户
        ResultObject ro = TokenManager.register(user, userInfo);
        if (100 != ro.getResult()) {
            return new ResultObject(ro.getResult(), ro.getMessage(), null);
        }
        String userId = user.getId();
        // 记录用户状态
        UserValidInfo validInfo = new UserValidInfo();
        validInfo.setUserId(userId);
        validInfo.setChangeStatus(Integer.parseInt(status));
        validInfo.setChangeTime(new Date());
        validInfo.setOperator(TokenManager.getTokenId());
        validInfo.setOperateReason("add user");
        validInfo.setCreateUser(TokenManager.getTokenId());
        userValidInfoService.insert(validInfo);
        // 记录用户组织机构
        UserOrg userOrg = new UserOrg();
        userOrg.setUserId(userId);
        userOrg.setOrgId(org);
        userOrg.setCreateUser(TokenManager.getTokenId());
        userOrgService.insert(userOrg);
        // 记录用户角色
        String[] roles = role.split(",");
        if (roles.length > 0) {
            Arrays.stream(roles).forEach(item -> {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(item);
                userRole.setCreateUser(TokenManager.getTokenId());
                userRoleService.insert(userRole);
            });
        }

        return new ResultObject(200, "success", user.getId());
    }

    /**
     * 保存修改信息
     *
     * @param map 信息实体类
     * @return 结果
     */
    @RequestMapping(value = "/save", method = RequestMethod.PUT)
    public ResultObject edit(@RequestBody Map map) {
        // 接收参数
        String id = String.valueOf(map.get("id"));
        String name = String.valueOf(map.get("name"));
        String mobile = String.valueOf(map.get("mobile"));
        String status = String.valueOf(map.get("status"));
        String org = String.valueOf(map.get("org"));
        String role = String.valueOf(map.get("role"));
        if (StringUtils.isBlank(id)) {
            return new ResultObject(500, "user id is blank.", null);
        }
        User user = userService.selectByPrimaryKey(id);
        if (user == null) {

            return new ResultObject(500, "user not found.", null);
        }
        UserInfo info = userInfoService.selectByUserId(id);
        if(!mobile.equals(info.getTel())){
            UserInfo ui = new UserInfo();
            ui.setTel(mobile);
            ui = userInfoService.selectOne(ui);
            if(ui !=null){
                ResultObject ro = new ResultObject();
                ro.setResult(505);
                ro.setMessage("Tel[" + mobile+ "] is already exist!");
                return ro;
            }
        }
        boolean changedStatus = false;
        // 记录是否改变了用户状态
        if (!status.equals(user.getStatus())) {
            changedStatus = true;
        }
        // 编辑用户详情
        if (StringUtils.isNotBlank(name)
                || StringUtils.isNotBlank(mobile)) {
            UserInfo userInfo = userInfoService.selectByUserId(id);
            userInfo.setName(name);
            userInfo.setTel(mobile);
            userInfo.setUpdateUser(TokenManager.getTokenId());
            userInfoService.update(userInfo);
        }

        // 新增用户状态记录
        if (changedStatus) {
            UserValidInfo validInfo = new UserValidInfo();
            validInfo.setUserId(id);
            validInfo.setChangeStatus(Integer.parseInt(status));
            validInfo.setChangeTime(new Date());
            validInfo.setOperator(TokenManager.getTokenId());
            validInfo.setOperateReason("edit user");
            validInfo.setCreateUser(TokenManager.getTokenId());
            userValidInfoService.insert(validInfo);
            user.setStatus(status);
            userService.update(user);
        }
        // 编辑用户组织机构
        if (StringUtils.isNotBlank(org)) {
            UserOrg userOrg = userOrgService.selectByUserId(id);
            userOrg.setOrgId(org);
            userOrg.setUpdateUser(TokenManager.getTokenId());
            userOrgService.update(userOrg);
        }
        //编辑用户角色
        if (StringUtils.isNotBlank(role)) {
            // 获取原角色
            List<UserRole> oldAllRoles = userRoleService.selectUserRoleListByUserId(id);
            // 编辑用户角色
            String[] rolesStr = role.split(",");
            if (rolesStr.length == 0) {
                // 被除去了所有角色
                oldAllRoles.forEach(item -> userRoleService.delete(item.getId()));
            } else {
                List<String> newAllRoles = Arrays.stream(rolesStr).collect(Collectors.toList());
                // 新角色列表
                for (String roleId : newAllRoles) {
                    boolean isExist = false;
                    for (UserRole userRole : oldAllRoles) {
                        if (userRole.getRoleId().equals(roleId)) {
                            isExist = true;
                            break;
                        }
                    }
                    // 不存在则新增
                    if (!isExist) {
                        UserRole userRole = new UserRole();
                        userRole.setUserId(id);
                        userRole.setRoleId(roleId);
                        userRole.setCreateUser(TokenManager.getTokenId());
                        userRoleService.insert(userRole);
                    }
                }
                // 免去的角色
                for (UserRole userRole : oldAllRoles) {
                    boolean hasRole = false;
                    for (String roleId : newAllRoles) {
                        if (roleId.equals(userRole.getRoleId())) {
                            hasRole = true;
                        }
                    }
                    if (!hasRole) {
                        userRoleService.delete(userRole.getId());
                    }
                }
            }
        }
        return new ResultObject(200, "success", id);
    }

    /**
     * 编辑用户
     *
     * @param map 增加信息
     * @return 结果
     */
    @RequestMapping(value = "/resetPwd", method = RequestMethod.PUT)
    public ResultObject resetPwd(@RequestBody Map map) {
        // 接收参数
        String id = String.valueOf(map.get("id"));
        String pwd = String.valueOf(map.get("pwd"));
        if (StringUtils.isBlank(id)) {
            return new ResultObject(500, "user id is blank.", null);
        }
        User user = userService.selectByPrimaryKey(id);
        if (user == null) {
            return new ResultObject(500, "user not found.", null);
        }
        user.setPassword(pwd);
        ResultObject ro = TokenManager.editUser(user, null);
        if (ro.getResult() == 102) {
            return new ResultObject(501, "user is not exist", null);
        }
        return new ResultObject(200, "success", null);
    }

    /**
     * 删除信息
     *
     * @param id 主键
     * @return 结果
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public ResultObject delete(@PathVariable String id) {
        // 查询当前用户的机构id
        String userId = TokenManager.getTokenId();
        UserOrg userOrg = new UserOrg();
        userOrg.setUserId(userId);
        UserOrg userOrg1 = userOrgService.selectOne(userOrg);
        // 查询子组织机构列表
        List<Organizations> organizationsList = organizationsService.selectSubList(userOrg1.getOrgId());
        // 转化为逗号分隔的字符串
        String orgIds = StringUtils.collectionsToCommas(
                organizationsList.stream().map(Organizations::getId).collect(Collectors.toList()));

        PageInfo pageInfo = userService.selectSubUserPageList(orgIds,
                null, 1, 0);
        boolean isExist = false;
        for (Object o : pageInfo.getList()) {
            User user = (User) o;
            if (user.getId().equals(id)) {
                isExist = true;
            }
        }
        if (isExist) {
            ResultObject ro = TokenManager.deleteUser(id);
            //删除用户对应的组织机构
            UserOrg userOrg2 = new UserOrg();
            userOrg2.setUserId(id);
            userOrg2 = userOrgService.selectOne(userOrg2);
            if (userOrg2 != null) {
                userOrgService.delete(userOrg2.getId());
            }
            if (ro.getResult() == 102) {
                return new ResultObject(501, "user is not exist!", null);
            }
        }
        return new ResultObject(200, "success", null);
    }

    /**
     * 获取当前用户的子组织机构(不包含本身所在组织机构)
     * @return
     */
    @RequestMapping(value = "/getSubOrgs", method = RequestMethod.GET)
    public ResultObject getSubOrgs() {
        String userId = TokenManager.getTokenId();
        return new ResultObject(200, "success", crmUserManagerService.getOrgListByUserId(userId));
    }

    /**
     * 获取当前用户的子角色机构(包含本组织机构创建的角色)
     * @return
     */
    @RequestMapping(value = "/getSubRoles", method = RequestMethod.GET)
    public ResultObject getRoles() {
        List<Role> roles = roleDao.selectList(null);
        return new ResultObject(200, "success", roles);
    }

}
